package cn.rtplay.esp32camcar.toolUtils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;

import java.io.File;
import java.util.ArrayList;
import java.util.Objects;

public class AppVersions {
    private static final AppVersions instance = new AppVersions();
    private String mVersionName;
    private String mLocalAPKName;
    private String mLocalLoadName;
    private String mLocalConfName;

    private AppVersions() {
    }

    public static AppVersions getInstance() {
        return instance;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersionName(Context context) {
        if (mVersionName == null) {
            PackageManager manager = context.getPackageManager();
            try {
                PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                mVersionName = info.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return mVersionName;
        }
        return mVersionName;
    }

    /**
     * 获取存储路径
     */
    public String getFilePath(Context context, String dir) {
        String directoryPath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {//判断外部存储是否可用
            directoryPath = Objects.requireNonNull(context.getExternalFilesDir(dir)).getAbsolutePath();
        } else {//没外部存储就使用内部存储
            directoryPath = context.getFilesDir() + File.separator + dir;
        }
        File file = new File(directoryPath);
        if (!file.exists()) {//判断文件目录是否存在
            boolean mkdirs = file.mkdirs();
        }
        return directoryPath;
    }

    /**
     * 获取指定目录内所有文件路径
     *
     * @param dirPath 需要查询的文件目录
     * @param _type   查询类型，比如mp3什么的
     */
    private ArrayList<String> getAllFiles(String dirPath, String _type) {
        File file = new File(dirPath);
        if (!file.exists()) {//判断路径是否存在
            return null;
        }
        File[] files = file.listFiles();
        if (files == null) {//判断权限
            return null;
        }
        ArrayList<String> fileList = new ArrayList<>();
        for (File _file : files) {//遍历目录
            if (_type == null) {
                if (_file.isFile()) {
                    String _name = _file.getName();
                    //String filePath = _file.getAbsolutePath();//获取文件路径
                    String fileName = _file.getName().substring(0, _name.length());//获取文件名
                    fileList.add(fileName);
                } else if (_file.isDirectory()) {//查询子目录
                    getAllFiles(_file.getAbsolutePath(), null);
                }
            } else {
                if (_file.isFile() && _file.getName().endsWith(_type)) {
                    String _name = _file.getName();
                    //String filePath = _file.getAbsolutePath();//获取文件路径
                    String fileName = _file.getName().substring(0, _name.length() - _type.length());//获取文件名
                    fileList.add(fileName);
                } else if (_file.isDirectory()) {//查询子目录
                    getAllFiles(_file.getAbsolutePath(), _type);
                }
            }
        }
        return fileList;
    }

    /**
     * 获取本地apk版本号
     * 文件格式:'esp32car_Vx.x.xxxx.apk'
     */
    public String getLocalAPKName(Context context) {
        if (mLocalAPKName == null) {
            mLocalAPKName = "";
            String filePath = getFilePath(context, "apk");
            ArrayList<String> fileList = getAllFiles(filePath, ".apk");
            if (fileList != null) {
                for (String fileName : fileList) {
                    String[] fileEle = fileName.split("_");
                    if (fileEle.length != 2) {
                        continue;
                    }
                    String[] fileVer = fileEle[1].split("\\.");
                    if (fileVer.length != 3) {
                        continue;
                    }
                    if (mLocalAPKName.equals("")) {
                        mLocalAPKName = fileEle[1].substring(1);
                    } else if (mLocalAPKName.compareTo(fileEle[1].substring(1)) < 0) {
                        mLocalAPKName = fileEle[1].substring(1);
                    }
                }
            }
            return mLocalAPKName;
        }
        return mLocalAPKName;
    }

    /**
     * 获取本地load版本号
     * 文件格式2019-10-25001727.mp4
     */
    public String getLocalLoadName(Context context) {
        if (mLocalLoadName == null) {
            mLocalLoadName = "";
            String filePath = getFilePath(context, "load");
            ArrayList<String> fileList = getAllFiles(filePath, null);
            if (fileList != null) {
                for (String fileName : fileList) {
                    String[] fileEle = fileName.split("\\.");
                    if (fileEle.length != 2) {
                        continue;
                    }
                    if (mLocalLoadName.equals("")) {
                        mLocalLoadName = fileEle[0];
                    } else if (mLocalLoadName.compareTo(fileEle[0]) < 0) {
                        mLocalLoadName = fileEle[0];
                    }
                }
            }
            return mLocalLoadName;
        }
        return mLocalLoadName;
    }

    /**
     * 获取本地conf版本号
     * 文件格式2019-10-25001727.conf
     */
    public String getLocalConfName(Context context) {
        if (mLocalConfName == null) {
            mLocalConfName = "";
            String filePath = getFilePath(context, "conf");
            ArrayList<String> fileList = getAllFiles(filePath, ".conf");
            if (fileList != null) {
                for (String fileName : fileList) {
                    if (mLocalConfName.equals("")) {
                        mLocalConfName = fileName;
                    } else if (mLocalConfName.compareTo(fileName) < 0) {
                        mLocalConfName = fileName;
                    }
                }
            }
            return mLocalConfName;
        }
        return mLocalConfName;
    }

    /**
     * 刷新loading文件版本号
     *
     * @param context context
     * @return 本地最新版本号
     */
    public String refreshLocalLoadName(Context context) {
        mLocalLoadName = "";
        String filePath = getFilePath(context, "load");
        ArrayList<String> fileList = getAllFiles(filePath, null);
        if (fileList != null) {
            for (String fileName : fileList) {
                String[] fileEle = fileName.split("\\.");
                if (fileEle.length != 2) {
                    continue;
                }
                if (mLocalLoadName.equals("")) {
                    mLocalLoadName = fileEle[0];
                } else if (mLocalLoadName.compareTo(fileEle[0]) < 0) {
                    mLocalLoadName = fileEle[0];
                }
            }
        }
        LogUtil.e("TAG", "1111"+mLocalLoadName);
        return mLocalLoadName;
    }

    /**
     * 刷新conf文件版本号
     *
     * @param context context
     * @return 本地最新版本号
     */
    public String refreshLocalConfName(Context context) {
        mLocalConfName = "";
        String filePath = getFilePath(context, "conf");
        ArrayList<String> fileList = getAllFiles(filePath, ".conf");
        if (fileList != null) {
            for (String fileName : fileList) {
                if (mLocalConfName.equals("")) {
                    mLocalConfName = fileName;
                } else if (mLocalConfName.compareTo(fileName) < 0) {
                    mLocalConfName = fileName;
                }
            }
        }
        return mLocalConfName;
    }
}
